package com.shf.util;

import com.alibaba.fastjson.JSONObject;

import com.shf.constants.URLConstants;
import okhttp3.*;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.util.Calendar;

/**
 * 百度云鉴权认证工具
 */
public class AuthUtil {

    private static Calendar expireDate;
    private static boolean flag = false;
    private static String accessToken;

    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    private static Boolean needAuth() {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, 1);
        return !flag || c.after(expireDate);
    }

    /**
     * 获取权限token
     * @return access_token
     */
    public static String getAccessToken(String clientId, String clientSecret) throws Exception {
        if (needAuth()) {
            flag = true;
            JSONObject auth = getAuth(clientId, clientSecret);
            accessToken = auth.getString("access_token");
            expireDate = Calendar.getInstance();
            expireDate.add(Calendar.SECOND, auth.getIntValue("expires_in"));
        }
        return accessToken;
    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    private static JSONObject getAuth(String clientId, String clientSecret) throws Exception {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url(String.format(URLConstants.BAIDU_AUTH_TOKEN, clientId, clientSecret))
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        if (response.code() != HttpStatus.OK.value()) {
            throw new RuntimeException("百度云AccessToken获取失败");
        }
        return JSONObject.parseObject(response.body().string());
    }
}

